package com.syni.mdd.sjb.tool.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.syni.mdd.sjb.common.component.utils.common.utils.RestTemplateUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.StringUtils;
import lombok.extern.log4j.Log4j2;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
@Log4j2
public class WeChatUtils {
    public static JSONObject findWeChatUserInfo(String openId, String accessToken){
        final int retryNum = 5;
        JSONObject ret = new JSONObject();
        AtomicInteger atomicInteger = new AtomicInteger();
        String url = "https://api.weixin.qq.com/sns/userinfo";
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("openid",openId);
        paramsMap.put("access_token",accessToken);
        paramsMap.put("lang","zh_CN");
        while (atomicInteger.getAndIncrement() < retryNum) {
            try {
                String responseBody = RestTemplateUtils.getForEntity(url, paramsMap);
                if (StringUtils.isNotBlank(responseBody)) {
                    JSONObject responseBodyMap = JSON.parseObject(responseBody);
                    if (responseBodyMap.size() > 0) {
                        ret.putAll(responseBodyMap);
                        break;
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
        }
        return ret;
    }
}
